package cn.com.wanywhn.a2017_04_02_bmob_brvah;

import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Adapter.PostListAdapter;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Bean.MyUser;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Bean.PostListBean;


@EActivity(R.layout.post_list_viewer)
public class PostListViewer extends BaseActivityToolBar implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener {
    int mcurrentnum = 0;
    PostListData mPostListData = new PostListData();
    List<PostListBean> data = new ArrayList<>();
    PostListAdapter adapter;
    @ViewById(R.id.SwipRefresh)
    SwipeRefreshLayout swiprefsh;
    @ViewById(R.id.post_list_recv)
    RecyclerView recv;
    MyUser muser = BmobUser.getCurrentUser(MyUser.class);

    @OnActivityResult(0)
    void onResult(int resultCode, Intent dat) {

        switch (resultCode) {
            case RESULT_OK:
                PostListBean tmp = dat.getParcelableExtra("ADD");
                tmp.setOwner(muser);
                /*
                 *  adapter.addData(tmp);
                 */
                PostListViewer.this.data.add(0, tmp);
                adapter.notifyDataSetChanged();
                break;
        }
    }

    @Click(R.id.fab)
    void startAdd() {
        Intent intent = new Intent(this, AddPostListItem_.class);
        startActivityForResult(intent, 0);
    }

    @AfterViews
    void initview() {
        setVisiableBackBtn();
        setVisiableToolBar(getIntent().getStringExtra("to"));
        initAdapter();
        initviews();
    }

    private void initAdapter() {
        adapter = new PostListAdapter(R.layout.post_item, data);
        adapter.setOnItemClickListener(this);
        adapter.setOnLoadMoreListener(this, recv);
        //设置自动加载数值
        adapter.setAutoLoadMoreSize(5);
    }

    private void initviews() {
        recv.setLayoutManager(new LinearLayoutManager(this));
        recv.setAdapter(adapter);
        swiprefsh.setOnRefreshListener(this);
        swiprefsh.setRefreshing(true);
        onRefresh();
    }


    @Override
    public void onRefresh() {
        data.clear();
        mPostListData.getData(0, 0);
        adapter.setEnableLoadMore(false);
        Log.d("DEBUG", "OnRefresh：" + data.size());
        updateRefreshData();
    }

    @UiThread(delay = 1900)
    void updateRefreshData() {
        adapter.notifyDataSetChanged();
        swiprefsh.setRefreshing(false);
        adapter.setEnableLoadMore(true);
        adapter.setAutoLoadMoreSize(5);
    }

    @Override
    public void onLoadMoreRequested() {
        swiprefsh.setEnabled(false);

        mcurrentnum = data.size();

        mPostListData.getData(1, 0);
        Log.d("DEBUG", "OnLoadMoreRequested");
        updateLoadMore();
    }

    @UiThread(delay = 2000)
    void updateLoadMore() {
        adapter.setNewData(data);
        //判断加载是否完成
        if (data.size() - mcurrentnum < 15)
            adapter.loadMoreEnd(false);
        else
            adapter.loadMoreComplete();
        swiprefsh.setEnabled(true);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        String title = data.get(position).getTitle();
        Toast.makeText(this, title, Toast.LENGTH_SHORT).show();
    }


    public class PostListData {
        final int[] currentpage = {1};
        final static int limit = 15;

    /*
     * 分页获取数据
     * @param actiontype 操作类型(0:刷新,1:加载更多)
     * @param page  页码
     */

        public List<PostListBean> getData(final int actiontype, final int page) {
            BmobQuery<PostListBean> query = new BmobQuery<PostListBean>();
            if (actiontype == 0) {
                currentpage[0] = 0;
            } else {
                query.setSkip((currentpage[0] + 1) * limit);
            }

            query.setLimit(limit);
            query.order("-createdAt");
            query.findObjects(new FindListener<PostListBean>() {
                @Override
                public void done(List<PostListBean> list, BmobException e) {
                    if (e == null) {
//                        mlist.clear();
                        if (actiontype == 0) {
//                        mlist.removeAll(mlist);
                            currentpage[0] = 0;
                        } else {
                            currentpage[0]++;
                        }
                        System.out.println("测试测试" + list.size() + "测试测试");
//                        mlist.addAll(list);
                        upd(list, actiontype);

                    } else {
                        System.err.println("!!!!!!!!!!!!!" + e.toString() + "!!!!!!!!!!!");
                    }
                }
            });
            return null;


        }

    }

    @UiThread
    void upd(List<PostListBean> item, int type) {
        if (type == 0)
            data.clear();
        data.addAll(item);
    }

}
